;
(function($) {

	var LightBox = function() {
		var self = this;

		//创建遮罩和弹出框
		this.popupMask = $('<div id="G-lightbox-mask">');
		this.popupWin = $('<div id="G-lightbox-popup">');

		//保存body
		this.bodyNode = $(document.body);

		//渲染剩余的Dom，并且插入到body
		this.renderDOM();

		//预览区域
		this.picViewArea = this.popupWin.find('div.lightbox-pic-view');

		this.popupPic = this.popupWin.find('img.lightbox-image');

		//标题区域
		this.picCatptionArea = this.popupWin.find('div.lightbox-caption-area');

		//切换按钮
		this.nextBtn = this.popupWin.find('span.lightbox-next-btn');
		this.prevBtn = this.popupWin.find('span.lightbox-prev-btn');

		//图片标题
		this.captionText = this.popupWin.find('p.lightbox-pic-desc');
		this.curentIndex = this.popupWin.find('span.lightbox-of-index');
		//关闭按钮
		this.colseBtn = this.popupWin.find('span.lightbox-close-btn');

		//事件委托，获取数组
		this.groupName = null;
		this.groupData = [];
		this.bodyNode.delegate('.js-lightbox,*[data-role=lightbox]',
			"click", function(e) {
				//阻止事件冒泡
				e.stopPropagation();

				//获取数据
				var currentGroupName = $(this).attr("data-group");
				if (currentGroupName != self.groupName) {
					self.groupName = currentGroupName;
					//获取图片组
					self.getGroup();
				}
				//初始化弹框
				self.initPopup($(this));
			});
		//关闭遮罩
		this.popupMask.click(function() {
			$(this).fadeOut();
			self.popupWin.fadeOut();
		});
		this.colseBtn.click(function() {
			self.popupMask.fadeOut();
			self.popupWin.fadeOut();
		});

		//上下切换图片(鼠标)
		var flag = true;

		this.nextBtn.hover(function() {
			if (!$(this).hasClass("disabled") && self.groupData.length > 1) {
				$(this).addClass("lightbox-next-btn-show");
			}
		}, function() {
			if (!$(this).hasClass("disabled") && self.groupData.length > 1) {
				$(this).removeClass("lightbox-next-btn-show");
			}
		}).click(function(e) {
			if (!$(this).hasClass("disabled") && self.flag) {
				self.flag = false;
				e.stopPropagation();
				self.goto("next");
			};
		});

		this.prevBtn.hover(function() {
			if (!$(this).hasClass("disabled") && self.groupData.length > 1) {
				$(this).addClass("lightbox-prev-btn-show");
			}
		}, function() {
			if (!$(this).hasClass("disabled") && self.groupData.length > 1) {
				$(this).removeClass("lightbox-prev-btn-show");
			}
		}).click(function(e) {
			if (!$(this).hasClass("disabled") && self.flag) {
				self.flag = false;
				e.stopPropagation();
				self.goto("prev");
			};
		});
		//上下切换图片(方向键)
		$(window).keyup(function(evt) {
			//keyCode: left 37 up 38  right 39 down 40  ESC 27
			if (evt.keyCode === 37 || evt.keyCode === 38) {
				self.goto("prev");
			} else if (evt.keyCode === 39 || evt.keyCode === 40) {
				self.goto("next");
			} else if (evt.keyCode === 27) {
				self.popupMask.click(); //ESC退出预览
			}
		})
	};
	LightBox.prototype = {
		goto: function(dir) {
			var self = this;
			if (dir === "next") {
				this.index++;
				if (this.index >= this.groupData.length - 1) {
					this.nextBtn.addClass("disabled").removeClass("lightbox-next-btn-show");
				};
				if (this.index != 0) {
					this.prevBtn.removeClass("disabled");
				};
				var src = this.groupData[this.index].src;
				this.loadPicSize(src);
			} else if (dir === "prev") {
				this.index--;
				if (this.index <= 0) {
					this.prevBtn.addClass("disabled").removeClass("lightbox-prev-btn-show");
				};
				if (this.index != this.groupData.length - 1) {
					this.nextBtn.removeClass("disabled");
				};
				var src = this.groupData[this.index].src;
				this.loadPicSize(src);
			};
		},
		loadPicSize: function(sourceSrc) {
			var self = this;
			//延迟50毫秒,为了更好的获取到图片的宽高
			this.preLoadImg(sourceSrc, function() {
				self.popupPic.attr("src", sourceSrc);
				setTimeout(function() {
					var picWidth = self.popupPic.width(),
						picHeight = self.popupPic.height();
					//console.log(picHeight,picWidth);
					self.changePic(picWidth, picHeight);
				}, 50);

			});
			self.popupPic.css({
				width: "auto",
				height: "auto"
			}).hide();
		},
		changePic: function(picWidth, picHeight) {
			var self = this,
				winWidth = $(window).width(),
				winHeight = $(window).height();
			//如果图片的宽高大于浏览器的宽高，就会出现溢出
			var scale = Math.min(winWidth / (picWidth + 10), winHeight / (picHeight + 10));
			picWidth = picWidth * scale;
			picHeight = picHeight * scale;

			this.picViewArea.animate({
				width: picWidth - 10,
				height: picHeight - 10
			});
			this.popupWin.animate({
				width: picWidth,
				height: picHeight,
				marginLeft: -(picWidth / 2),
				top: (winHeight - picHeight) / 2
			}, function() {
				self.popupPic.css({
					width: picWidth - 10,
					height: picHeight - 10,
				}).fadeIn();

				self.picCatptionArea.fadeIn();
				self.flag = true;
			});
			//设置描述文本
			//console.log(this.index);
			this.captionText.text(this.groupData[this.index].caption);
			this.curentIndex.text("当前索引：" + (this.index + 1) + "of " + this.groupData.length);
		},
		preLoadImg: function(src, callback) {
			var img = new Image();
			if (!!window.ActiveXObject) {
				img.onreadystatechange = function() {
					if (this.readyState == "complete") {
						callback();
					}
				};
			} else {
				img.onload = function() {
					callback();
				}
			}
			img.src = src;
		},
		getIndexOf: function(currentId) {
			var index = 0;
			$(this.groupData).each(function(i) {
				if (this.id === currentId) {
					return false;
				};
				index++;
			});
			return index;
		},
		showMaskAndPopup: function(sourceSrc, currentId) {
			var self = this;
			this.popupPic.hide();
			this.picCatptionArea.hide();
			this.popupMask.fadeIn();

			var winWidth = $(window).width();
			var winHeight = $(window).height();

			this.picViewArea.css({
				width: winWidth / 2,
				height: winHeight / 2
			});

			this.popupWin.fadeIn();

			var viewHeight = winHeight / 2 + 10;

			this.popupWin.css({
				width: winWidth / 2 + 10,
				height: winHeight / 2 + 10,
				marginLeft: -(winWidth / 2 + 10) / 2,
				top: -viewHeight
			}).animate({
				top: (winHeight - viewHeight) / 2
			}, function() {
				//加载显示图片的资源
				self.loadPicSize(sourceSrc);
			});

			//根据当前点击元素的id查找其在该组别中的索引
			this.index = this.getIndexOf(currentId);
			//console.log(this.index);
			//判断该组图片的总数
			var groupDataLength = this.groupData.length;
			if (groupDataLength > 0) {
				if (this.index === 0) {
					this.prevBtn.addClass("disabled");
					this.nextBtn.removeClass("disabled");
				} else if (this.index === groupDataLength - 1) {
					this.prevBtn.removeClass("disabled");
					this.nextBtn.addClass("disabled");
				} else {
					this.prevBtn.removeClass("disabled");
					this.nextBtn.removeClass("disabled");
				}
			}

		},
		initPopup: function(currentObj) {
			var self = this;
			var sourceSrc = currentObj.attr("data-source");
			var currentId = currentObj.attr("data-id");

			//获取id,找图片在数组中的位置
			this.showMaskAndPopup(sourceSrc, currentId);

		},
		getGroup: function() {
			var self = this;
			//根据当前组别获取页面上相同组的数据
			var grouplist = this.bodyNode.find("*[data-group=" + this.groupName + "]");
			//清空数组
			self.groupData.length = 0;
			grouplist.each(function() {
				self.groupData.push({
					src: $(this).attr("data-source"),
					id: $(this).attr("data-id"),
					caption: $(this).attr("data-caption"),
				});
			});
			//console.log(self.groupData);
		},
		renderDOM: function() {

			var strDom = '<div class="lightbox-pic-view">' //piv-view start
				+ '<span class="lightbox-btn lightbox-prev-btn"></span>' //prevBtn
				+ '<img class="lightbox-image" src="images/2-2.jpg">' //pic
				+ '<span class="lightbox-btn lightbox-next-btn"></span>' //nextBtn
				+ '</div>' //piv-view end
				+ '<div class="lightbox-pic-caption">' //pic-caption start
				+ '<div class="lightbox-caption-area">' //caption-area start
				+ '<p class="lightbox-pic-desc"></p>' //picDesc
				+ '<span class="lightbox-of-index">当前索引: 0 of 0</span>' //picIndex 
				+ '</div>' //caption-area end
				+ '<span class="lightbox-close-btn"></span>' //closeBtn
				+ '</div>'; //pic-caption end
			//插入到popupWin
			this.popupWin.html(strDom);
			//把遮罩和弹出框插入到body
			this.bodyNode.append(this.popupMask);
			this.bodyNode.append(this.popupWin);
		}
	};
	window["LightBox"] = LightBox;
})(jQuery);